// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
// import JsPDF from 'jspdf'
// console.log(4, jsPDF)
/**
 * @param {elementNode|String} body dom节点或者html字符串
 * @param {String} scale 节点放大倍数
 */
const getCanvasContent = (body, scale = '1') => {
  // table字段太多是要缩放打印
  let width = 100 / Number(scale)
  body = body.nodeType ? body.outerHTML : body
  const div = document.createElement('div')
  div.style = `height:auto; margin: 0; padding: 20px 40px; width: ${width}%; transform:scale(${scale});transform-origin: left top; position:absolute; left:-9999px; top:-9999px;`
  div.innerHTML = body
  document.body.append(div)
  // 打印弹窗
  return div
}
export default{
  /**
   *
   * @param {Vue} Vue
   * @param {*} options 无用
   */
  install (Vue, options) {
    /**
     * @param {String} str 节点id或者
     * @param {String} title
     * @description 如果str是id  那么下载pdf后删除canvasNode节点
     */
    Vue.prototype.getPdf = function (str = '#pdfDom', title, scale = '1') {
      const canvasNode = str[0] === '#' ? document.querySelector(str) : getCanvasContent(str, scale)
      html2Canvas(canvasNode, {
        allowTaint: true
      }).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        const JsPDF = window.jsPDF
        let PDF = new JsPDF('', 'pt', 'a4')
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save(title + '.pdf')
        if (str[0] !== '#') {
          document.body.removeChild(canvasNode)
        }
      })
    }
  }
}
